/* UI hooks */
function clearUI()                     { alert("clearUI is not implemented"); }
function displayWinner(winner_message) { alert("displayWinner is not implemented"); }
function hideWinner()                  { alert("hideWinner is not implemented"); }
function setCellClickFunction(func)    { alert("setCellClickFunction is not implemented"); }
function setRestartClickFunction(func) { alert("setRestartClickFunction is not implemented"); }
function clearButtons() {}
function setButtons(board) {}

/* Main Game Handling class */
var RockPaperScissors = {
	result : [0, 0],
	board : [ "", "" ], // Keeps a record of the RockPaperScissors Board
	win : false, // records who won if the game is over

	setupGame : function() {
		// Add on-click events to each of the boxes of the board
		setCellClickFunction(function(e) {
			id = $(this).attr("id");
			RockPaperScissors.move(id);
		});

		// Button for playing again.
		setRestartClickFunction(function() {
			RockPaperScissors.restartGame();
		});

		clearUI();
	},

	/* Clears and starts a new game with a new board */
	restartGame : function() {
		// Hide the menu
		hideWinner();

		// Clear the board
		this.board = ["", ""];
		this.win = false;

		// Clear the UI
		clearUI();
	},

	/* Handles clicks spaces on the board */
	move : function(id) {
		var player = id.substr(0, 1);
		var num = id.substring(1);

		// If the game isn't over, go there!
		if (!this.win) {
			this.board[player] = num;

			clearButtons();
			setButtons(this.board);

			this.win = this.check4Win();
			if (this.win) {
				this.endGame();
			}
		}
	},

	/* Display who won and options for new games */
	endGame : function() {
		var winner_message = "";
		if (this.win == "Cat") {
			winner_message = "Cat's Game.";
		} else {
			winner_message = "Player '"+ this.win +"' wins!";
		}

		displayWinner(winner_message);
	},

	// If any of these patters of board spaces have all X's or all O's somebody won!
	winning_moves : [["RS"], ["PR"], ["SP"]],

	/* Check for whether someone won the game of it was a Cat's game. */
	check4Win : function() {

		// Loop through all possible winning combinations
		for (w in this.winning_moves) {
			var pattern = this.winning_moves[w];
			var x = this.board[0] + this.board[1];
			var o = this.board[1] + this.board[0];

			if (x == pattern) {
				this.result[0] += 1;
				return "X"; // X Won!
			}
			if (o == pattern) {
				this.result[1] += 1;
				return "O"; // O Won!
			}
		}

		// Check if all spaces in the board are filled, then its a Cat's game
		var cnt = 0;
		for (s in this.board) {
			if (this.board[s]) {
				cnt += 1;
			}
		}

		if (cnt == 2) {
			return "Cat"; // Cat's game!
		}
	}
};

$(document).ready(function() {
	// Start a game!
	RockPaperScissors.setupGame();
});
